package com.tencent.wxcloudrun.controller;

import com.tencent.wxcloudrun.constants.Constants;
import com.tencent.wxcloudrun.model.Token;
import com.tencent.wxcloudrun.model.User;
import com.tencent.wxcloudrun.service.TokenService;
import com.tencent.wxcloudrun.service.UserService;
import com.tencent.wxcloudrun.utils.UUIDUtil;
import com.tencent.wxcloudrun.view.BaseVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/api/user")
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private TokenService tokenService;

    /**
     * 查询所用用户的账号，供用户在注册时候使用
     * @return
     */
    @RequestMapping("/serachAllAccount")
    public BaseVO serachAllAccount(){
        List<String> allAccList = userService.findAllAccount();
        return new BaseVO(Constants.BASEVO_CODE_SUCCESS,"",allAccList);
    }

    /**
     * 用户注册
     * @param user 用户的实体对象,包含用账号,密码和姓名
     * @return
     */
    @RequestMapping("/regist")
    public BaseVO regist(User user) {
        user.setCoin(0L);
        user.setDataStatus(1);
        user.setCreateTime(new Date());
        int count = userService.addRegistUser(user);
        if (count > 0) {
            return new BaseVO(Constants.BASEVO_CODE_SUCCESS, "恭喜您,注册成功!");
        }
        return new BaseVO(Constants.BASEVO_CODE_FAIL, "系统繁忙,请稍后重试...");
    }


    @RequestMapping("/login")
    public BaseVO login(String account, String password) {

        //调用service层方法查询用户
        User loginUser = userService.login(account, password);
        //登录失败
        if (loginUser == null) {
            return new BaseVO(Constants.BASEVO_CODE_FAIL, "用户名或者密码错误");
        } else if (loginUser.getDataStatus() == 2) {
            return new BaseVO(Constants.BASEVO_CODE_FAIL, "用户状态已失效");
        }
        //登录成功
        //查询用户是否有token
        Token token = tokenService.findTokenByUserId(loginUser.getId());
        //没有token,新建一个
        if (token == null) {
            token = new Token();
            token.setValue(UUIDUtil.getUUID());
            token.setCreateTime(new Date());
            token.setExpireTime(new Date(new Date().getTime() + 24 * 60 * 60 * 1000)); //有效期为一天
            token.setDataStatus(1);
            token.setUserId(loginUser.getId());
            tokenService.addToken(token);
        }
        //token过期，把token的状态置为2
        if (token.getExpireTime().getTime() < new Date().getTime()) {
            token.setDataStatus(2);
        }
        return new BaseVO(Constants.BASEVO_CODE_SUCCESS, "登录成功", token);
    }

}
